package com.universal.schedule.fragments;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.melnykov.fab.FloatingActionButton;
import com.universal.schedule.AddScheduleActivity;
import com.universal.schedule.R;
import com.universal.schedule.ScheduleDetailActivity;
import com.universal.schedule.db.DBManager;
import com.universal.schedule.db.DatabaseHelper;
import com.universal.schedule.timetable.ColorUtils;
import com.universal.schedule.timetable.CornerTextView;
import com.universal.schedule.timetable.CourseModel;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class ScheduleFragments  extends Fragment{
	private View layout;
	private LayoutInflater mInflater;
	LinearLayout weekNames;
	LinearLayout sections;
	List<LinearLayout> mWeekViews;
	private int itemHeight;
	private int maxSection = 12;
	private FloatingActionButton mFab;
	private ArrayList<CourseModel> courseModelList=new ArrayList<>();
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		initUI(inflater, container);
		return layout;
	}

	private void initUI(LayoutInflater inflater, ViewGroup container) {
		if(layout==null)
		{
			mInflater=inflater;
			layout = inflater.inflate(R.layout.fragments_schedule, container, false);
			findView();
			itemHeight = getResources().getDimensionPixelSize(R.dimen.sectionHeight);
			initWeekNameView();
			initSectionView();
			initWeekCourseView();
		}
	}

	private void findView() {
		mWeekViews=new ArrayList<>();
		weekNames = (LinearLayout) layout.findViewById(R.id.weekNames);
		sections = (LinearLayout) layout.findViewById(R.id.sections);
		LinearLayout week1 = (LinearLayout) layout.findViewById(R.id.weekPanel_1);
		LinearLayout week2 = (LinearLayout) layout.findViewById(R.id.weekPanel_2);
		LinearLayout week3 = (LinearLayout) layout.findViewById(R.id.weekPanel_3);
		LinearLayout week4 = (LinearLayout) layout.findViewById(R.id.weekPanel_4);
		LinearLayout week5 = (LinearLayout) layout.findViewById(R.id.weekPanel_5);
		LinearLayout week6 = (LinearLayout) layout.findViewById(R.id.weekPanel_6);
		LinearLayout week7 = (LinearLayout) layout.findViewById(R.id.weekPanel_7);

		mFab = (FloatingActionButton) layout.findViewById(R.id.fab);

		mWeekViews.add(week1);
		mWeekViews.add(week2);
		mWeekViews.add(week3);
		mWeekViews.add(week4);
		mWeekViews.add(week5);
		mWeekViews.add(week6);
		mWeekViews.add(week7);



		mFab.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(getActivity(), AddScheduleActivity.class);
				startActivityForResult(intent, 1000);

			}
		});

	}


	/**
	 * 初始化课程表
	 */
	private void initWeekCourseView() {
		for (int i = 0; i < mWeekViews.size(); i++) {
			initWeekPanel(mWeekViews.get(i), getCourseData()[i]);
		}
	}

	/**
	 * 添加课程表
	 */
	private void addWeekCourseView() {
		for (int i = 0; i < mWeekViews.size(); i++) {
			initWeekPanel(mWeekViews.get(i), getSingleData()[i]);
		}
	}

	/**
	 * 顶部周一到周日的布局
	 **/
	private void initWeekNameView() {
		for (int i = 0; i < mWeekViews.size() + 1; i++) {
			TextView tvWeekName = new TextView(getActivity());
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
			lp.gravity = Gravity.CENTER | Gravity.CENTER_HORIZONTAL;
			if (i != 0) {
				lp.weight = 1;
				tvWeekName.setText("周" + intToZH(i));
				if (i == getWeekDay()) {
					tvWeekName.setTextColor(Color.parseColor("#FF0000"));
				} else {
					tvWeekName.setTextColor(Color.parseColor("#4A4A4A"));
				}
			} else {
				lp.weight = 0.8f;
				tvWeekName.setText(getMonth() + "月");
			}
			tvWeekName.setGravity(Gravity.CENTER_HORIZONTAL);
			tvWeekName.setLayoutParams(lp);
			weekNames.addView(tvWeekName);
		}
	}

	/**
	 * 左边节次布局，设定每天最多12节课
	 */
	private void initSectionView() {
		for (int i = 1; i <= maxSection; i++) {
			TextView tvSection = new TextView(getActivity());
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelSize(R.dimen.sectionHeight));
			lp.gravity = Gravity.CENTER;
			tvSection.setGravity(Gravity.CENTER);
			tvSection.setText(String.valueOf(i));
			tvSection.setLayoutParams(lp);
			sections.addView(tvSection);
		}
	}

	/**
	 * 当前星期
	 */
	public int getWeekDay() {
		int w = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1;
		if (w <= 0) {
			w = 7;
		}
		return w;
	}

	/**
	 * 当前月份
	 */
	public int getMonth() {
		int w = Calendar.getInstance().get(Calendar.MONTH) + 1;
		return w;
	}

	/**
	 * 每次刷新前清除每个LinearLayout上的课程view
	 */
	private void clearChildView() {
		for (int i = 0; i < mWeekViews.size(); i++) {
			if (mWeekViews.get(i) != null)
				if (mWeekViews.get(i).getChildCount() > 0)
					mWeekViews.get(i).removeAllViews();
		}
	}


	public void initWeekPanel(LinearLayout ll, List<CourseModel> data) {

		if (ll == null || data == null || data.size() < 1)
			return;

		CourseModel firstCourse = data.get(0);
		for (int i = 0; i < data.size(); i++) {
			final CourseModel courseModel = data.get(i);

			if (courseModel.getSection() == 0 || courseModel.getSectionSpan() == 0)
				return;
			FrameLayout frameLayout = new FrameLayout(getActivity());

			CornerTextView tv = new CornerTextView(getActivity(),
					ColorUtils.getCourseBgColor(courseModel.getCourseFlag()),
					dip2px(getActivity(), 3));
			LinearLayout.LayoutParams frameLp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					itemHeight * courseModel.getSectionSpan());
			LinearLayout.LayoutParams tvLp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT);

			if (i == 0) {
				frameLp.setMargins(0, (courseModel.getSection() - 1) * itemHeight, 0, 0);
			} else {
				frameLp.setMargins(0, (courseModel.getSection() - (firstCourse.getSection() + firstCourse.getSectionSpan())) * itemHeight, 0, 0);
			}
			tv.setLayoutParams(tvLp);
			tv.setGravity(Gravity.CENTER);
			tv.setTextSize(12);
			tv.setTextColor(Color.parseColor("#FFFFFF"));
			tv.setText(courseModel.getCourseName() + "\n @" + courseModel.getClassRoom());

			frameLayout.setLayoutParams(frameLp);
			frameLayout.addView(tv);
			frameLayout.setPadding(2, 2, 2, 2);
			ll.addView(frameLayout);
			firstCourse = courseModel;
			tv.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					if(null!=courseModel){
						Intent intent = new Intent(getActivity(), ScheduleDetailActivity.class);
						intent.putExtra("schedule", courseModel);
						startActivity(intent);
					}
				}
			});
		}
	}

	/**
	 * Toast
	 */
	private void showToast(String msg) {
		if (TextUtils.isEmpty(msg))
			return;
		Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 数字转换中文
	 */
	public static String intToZH(int i) {
		String[] zh = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
		String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十"};

		String str = "";
		StringBuffer sb = new StringBuffer(String.valueOf(i));
		sb = sb.reverse();
		int r = 0;
		int l = 0;
		for (int j = 0; j < sb.length(); j++) {
			r = Integer.valueOf(sb.substring(j, j + 1));
			if (j != 0)
				l = Integer.valueOf(sb.substring(j - 1, j));
			if (j == 0) {
				if (r != 0 || sb.length() == 1)
					str = zh[r];
				continue;
			}
			if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 9) {
				if (r != 0)
					str = zh[r] + unit[j] + str;
				else if (l != 0)
					str = zh[r] + str;
				continue;
			}
			if (j == 4 || j == 8) {
				str = unit[j] + str;
				if ((l != 0 && r == 0) || r != 0)
					str = zh[r] + str;
				continue;
			}
		}
		if (str.equals("七"))
			str = "日";
		return str;
	}

	private  List<CourseModel>[] getCourseData(){
		List<CourseModel> courseModels[] = new ArrayList[7];

		for (int i = 0; i < courseModels.length; i++) {
			courseModels[i] = new ArrayList<>();
		}

		List<CourseModel> models_1 = new ArrayList<>();
		List<CourseModel> models_2 = new ArrayList<>();
		List<CourseModel> models_3 = new ArrayList<>();
		List<CourseModel> models_4 = new ArrayList<>();
		List<CourseModel> models_5 = new ArrayList<>();
		List<CourseModel> models_6 = new ArrayList<>();
		List<CourseModel> models_7 = new ArrayList<>();
		courseModelList.clear();
		Cursor mCursor = DBManager.getInstance(getActivity()).selectByTableName(DatabaseHelper.SCHEDULE_TABLE);
		if (mCursor.moveToFirst()) {
			do {
				CourseModel courseModel = new CourseModel(mCursor.getInt(0), mCursor.getString(1), mCursor.getInt(2), mCursor.getInt(3), mCursor.getInt(4), mCursor.getString(5), mCursor.getInt(6), mCursor.getString(7));
				courseModelList.add(courseModel);
			} while (mCursor.moveToNext());
		}

		for (int i = 0; i < courseModelList.size(); i++) {
			int week = courseModelList.get(i).getWeek();
			if(week==1){
				models_1.add(courseModelList.get(i));
			}else if(week==2){
				models_2.add(courseModelList.get(i));
			}else if(week==3){
				models_3.add(courseModelList.get(i));
			}else if(week==4){
				models_4.add(courseModelList.get(i));
			}else if(week==5){
				models_5.add(courseModelList.get(i));
			}else if(week==6){
				models_6.add(courseModelList.get(i));
			}else if(week==7){
				models_7.add(courseModelList.get(i));
			}
		}
		if(models_1.size()!=0){
			courseModels[0].addAll(models_1);
		}

		if(models_2.size()!=0){
			courseModels[1].addAll(models_2);
		}

		if(models_3.size()!=0){
			courseModels[2].addAll(models_3);
		}

		if(models_4.size()!=0){
			courseModels[3].addAll(models_4);
		}

		if(models_5.size()!=0){
			courseModels[4].addAll(models_5);
		}

		if(models_6.size()!=0){
			courseModels[5].addAll(models_6);
		}

		if(models_7.size()!=0){
			courseModels[6].addAll(models_7);
		}

		return courseModels;
	}

	private  List<CourseModel>[] getSingleData(){
		List<CourseModel> courseModels[] = new ArrayList[7];

		for (int i = 0; i < courseModels.length; i++) {
			courseModels[i] = new ArrayList<>();
		}

		List<CourseModel> models_1 = new ArrayList<>();
		List<CourseModel> models_2 = new ArrayList<>();
		List<CourseModel> models_3 = new ArrayList<>();
		List<CourseModel> models_4 = new ArrayList<>();
		List<CourseModel> models_5 = new ArrayList<>();
		List<CourseModel> models_6 = new ArrayList<>();
		List<CourseModel> models_7 = new ArrayList<>();
		courseModelList.clear();
		Cursor mCursor = DBManager.getInstance(getActivity()).
				selectLastField(DatabaseHelper.SCHEDULE_TABLE);
		if (mCursor.moveToFirst()) {
			CourseModel courseModel = new CourseModel(mCursor.getInt(0), mCursor.getString(1), mCursor.getInt(2), mCursor.getInt(3), mCursor.getInt(4), mCursor.getString(5), mCursor.getInt(6), mCursor.getString(7));
			courseModelList.add(courseModel);
		}

		for (int i = 0; i < courseModelList.size(); i++) {
			int week = courseModelList.get(i).getWeek();
			if(week==1){
				models_1.add(courseModelList.get(i));
			}else if(week==2){
				models_2.add(courseModelList.get(i));
			}else if(week==3){
				models_3.add(courseModelList.get(i));
			}else if(week==4){
				models_4.add(courseModelList.get(i));
			}else if(week==5){
				models_5.add(courseModelList.get(i));
			}else if(week==6){
				models_6.add(courseModelList.get(i));
			}else if(week==7){
				models_7.add(courseModelList.get(i));
			}
		}
		if(models_1.size()!=0){
			courseModels[0].addAll(models_1);
		}

		if(models_2.size()!=0){
			courseModels[1].addAll(models_2);
		}

		if(models_3.size()!=0){
			courseModels[2].addAll(models_3);
		}

		if(models_4.size()!=0){
			courseModels[3].addAll(models_4);
		}

		if(models_5.size()!=0){
			courseModels[4].addAll(models_5);
		}

		if(models_6.size()!=0){
			courseModels[5].addAll(models_6);
		}

		if(models_7.size()!=0){
			courseModels[6].addAll(models_7);
		}

		return courseModels;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		addWeekCourseView();
	}




}



